package cn.yonyong.base.project.service.impl;

import cn.yonyong.base.project.entity.TblImage;
import cn.yonyong.base.project.mapper.TblImageMapper;
import cn.yonyong.base.project.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true)
public class ImageServiceImpl implements ImageService{

    @Resource
    private TblImageMapper tblImageMapper;

    @Override
    @Transactional(readOnly = false)
    public Map<String, Object> saveImage(String url,String absolute_name, long file_size) {
        Map<String, Object> result_map = new HashMap<>();   //返回结果集
        Example example = new Example(TblImage.class);

        example.createCriteria()
                .andLike("url","%"+absolute_name)
                .andEqualTo("size",file_size);
        List<TblImage> query_list = tblImageMapper.selectByExample(example);
        if (null != query_list && query_list.size()>0){  //数据库中已经有该文件
            result_map.put("insert","exist");
            return result_map;
        }
        //不存在，准予添加
        TblImage tblImage = new TblImage();
        tblImage.setUrl(url);
        tblImage.setSize(file_size);
        tblImage.setDescription(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())+":添加");

        int flag = tblImageMapper.insert(tblImage);
        if (flag == 1){
            result_map.put("insert","success");
        }else {
            result_map.put("insert","fail");
        }
        return result_map;
    }

    @Override
    public Map<String, Object> getList() {
        Map<String, Object> result_map = new HashMap<>();
        List<TblImage> query_list = tblImageMapper.selectAll();
        result_map.put("list",query_list);
        return result_map;
    }
}
